<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/modules/Account/classes/PhpFox_ServiceSubscribe.class.php, $Author:  $ */



/** Service for working with subscribe
 *
 * @package module.account
 * @version $Id: PhpFox_ServiceSubscribe.class.php 223 2008-01-26 07:39:30Z phpfoxsv $
 *   Max Kovrigovich
 */
class PhpFox_Mod_Account_ServiceSubscribe extends BaseService
{
    function getTransactionById($iTransactId)
    {
        $oPayment = & new Payment('paypal');
		/* @var $oPayment Payment */

        //prepare payment transaction
	    $oSaleItem = &App::getModuleItem('Account', 'Sale');
        /* @var $oSaleItem PhpFox_Mod_Account_ItemSale */
        $oSaleItem->load($iTransactId);

	    return $oSaleItem->aData;
    }

    function processPostback()
    {
        $oPayment = & new Payment('paypal');
		/* @var $oPayment Payment */
	    if(!empty($_POST))
	    {
	        //get status
            list($iTransactId, $sStatus) = $oPayment->finishPayment($_POST);

            //analyze status and finish transaction
            $oSaleItem = &App::getModuleItem('Account', 'Sale');
            /* @var $oSaleItem PhpFox_Mod_Account_ItemSale */
            $oSaleItem->load($iTransactId);

            if ($sStatus == 'paid')
            {
                $oSaleItem->aData['status'] = 'approved';
                $oSaleItem->update(array('status'));

                //get account id
                $aTrans = $oSaleItem->aData;

                $oSrvAccount = $this->_oModule->getService('Account');
                /* @var $oSrvAccount PhpFox_Mod_Account_ServiceAccount */

                $oSrvAccount->setMembership($aTrans['account_id'], $aTrans['membership_id'], 1, $aTrans['accept_after_confirm']);
            }
            else
            {
                $oSaleItem->aData['status'] = 'canceled';
                $oSaleItem->update(array('status'));

				//get account id
                $aTrans = $oSaleItem->aData;

                $oSrvAccount = $this->_oModule->getService('Account');
                /* @var $oSrvAccount PhpFox_Mod_Account_ServiceAccount */

                $oSrvAccount->setMembership($aTrans['account_id'], 3, 1, 1);
            }
	        exit;
	    }
    }

    function addTransaction($oUser, $aMData, $bAcceptNow)
    {
        $oPayment = & new Payment('paypal');
		/* @var $oPayment Payment */

		$aMData['pay_type'] = ((strtolower($aMData['pay_type']) == 'monthly') ? 'monthly' : 'onetime');
		
        //prepare payment transaction
	    $oSaleItem = &App::getModuleItem('Account', 'Sale');
        /* @var $oSaleItem PhpFox_Mod_Account_ItemSale */

		$oSaleItem->aData['account_id']           = $oUser->aData['id'];
		$oSaleItem->aData['price']                = $aMData['price'];
		$oSaleItem->aData['accept_after_confirm'] = $bAcceptNow ? 1 : 0;
		$oSaleItem->aData['cdate']                = Database::date();
		$oSaleItem->aData['status']               = 'pending';
		$oSaleItem->aData['membership_id']        = $aMData['membership_id'];

		$iTransId = $oSaleItem->insert();

	    $sRequest = $oPayment->makePayment($iTransId,
	        $aMData['price'],
	        array('paddress'   => App::getSetting('payment_paypal_email'),
	              'account_id' => $oUser->aData['id'],
	              'pay_type' => $aMData['pay_type'],
	              'user'       => $oUser->aData['user'],
	              'email'      => $oUser->aData['email'],
	              'currency'   => App::getSetting('payment_paypal_currency')));
    }

    function getRemainderDaysCount($oUser)
    {
        assert($oUser != null);
        $oSecurityService = &$this->_oModule->getService('Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */

	    $sLastPayment = $oUser->aData['last_payment'];
	    $iMembershipId = $oUser->aData['type'];
	    $aMembershipData = $oSecurityService->getMembershipData($iMembershipId);
	    if ($aMembershipData['pay_type'] == 'onetime')
	    {
	        return 0;
	    }
	    $iLastPayment = strtotime($sLastPayment);

	    return ceil(($iLastPayment - time()) / 86400);
    }

    function _sendExpiresEmail($oUser)
    {
        assert($oUser != null);
        $oSecurityService = &$this->_oModule->getService('Security');
        /* @var $oSecurityService PhpFox_Mod_Account_ServiceSecurity */
        $oMailer = App::newObject('mail_Mailer');
		/* @var oMailer mail_Mailer */

        $aMembershipData = $oSecurityService->getMembershipData($oUser->aData['type']);
        $aVariables = array
        (
            'SUBSCRIBE_LINK'   => App::makeUrl('public.subscribe'),
            'USERNAME'         => $oUser->aData['user'],
            'MEMBERSHIP_TITLE' => $aMembershipData['title'],
        );
        $oMailer->send('email_membership_expires', $oUser->aData['email'], App::format('core.subscription.expires'), $aVariables);
    }

    function processExpiresMemberships()
    {
    	return true;

        $oAccountSrv = &$this->_oModule->getService('Account');
        /* @var $oAccountSrv PhpFox_Mod_Account_ServiceAccount */
        $oAccountItem = &$this->_oModule->getItem('Account');
        /* @var $oAccountItem PhpFox_Mod_Account_ItemAccount */

        $sLastSendDate = App::getSetting('last_membership_expires_sdate');
        $sCurrentDate = date('Y-m-d');
        if ($sLastSendDate == $sCurrentDate)
        {
            return false;
        }
        App::saveSetting('last_membership_expires_sdate', $sCurrentDate);
        $sSql = 'SELECT id '.
               ' FROM `'.App::getT('user').'` '.
               ' WHERE DATE(last_payment) = DATE_ADD(CURDATE(), INTERVAL 1 DAY)';
        $aRows = $oAccountItem->oDb->getRows($sSql);
        foreach ($aRows as $aRow)
        {
            $oUser = $oAccountSrv->getById($aRow['id']);
            $this->_sendExpiresEmail($oUser);
        }
        return true;
    }
}
?>